"""
下单任务处理模块
负责处理客户下单请求，收集订单信息
"""

import logging
import re
from typing import Dict, Any, List, Tuple

logger = logging.getLogger(__name__)

class OrderProcessingTask:
    """下单任务处理器"""
    
    def __init__(self):
        self.task_name = "下单"
        self.logger = logging.getLogger(f"{__name__}.OrderProcessingTask")
        
        # 订单信息字段
        self.order_fields = {
            "receiver": "收货人",
            "phone": "联系电话", 
            "address": "地址",
            "product_name": "商品名称",
            "color": "颜色",
            "quantity": "数量"
        }
    
    def can_handle(self, message: str, conversation_history: list) -> bool:
        """
        判断是否可以处理此消息
        
        Args:
            message: 客户消息
            conversation_history: 对话历史
            
        Returns:
            bool: 是否可以处理
        """
        # 下单关键词
        order_keywords = [
            '下单', '购买', '买', '订购', '订', '要', '需要', '想要',
            '下单吧', '购买吧', '买吧', '订购吧', '订吧'
        ]
        
        # 检查是否包含下单关键词
        for keyword in order_keywords:
            if keyword in message:
                return True
        
        # 检查是否包含订单信息（收货人、电话、地址等）
        if self._contains_order_info(message):
            return True
            
        return False
    
    def _contains_order_info(self, message: str) -> bool:
        """检查是否包含订单信息"""
        # 手机号模式
        phone_pattern = r'1[3-9]\d{9}'
        if re.search(phone_pattern, message):
            return True
        
        # 地址关键词
        address_keywords = ['区', '市', '省', '县', '街道', '路', '号']
        for keyword in address_keywords:
            if keyword in message:
                return True
        
        # 数量关键词
        quantity_keywords = ['件', '个', '台', '部', '本', '张']
        for keyword in quantity_keywords:
            if keyword in message:
                return True
        
        return False
    
    def process(self, message: str, conversation_history: list, customer_id: str, existing_order_info: Dict = None) -> Dict[str, Any]:
        """
        处理下单任务
        
        Args:
            message: 客户消息
            conversation_history: 对话历史
            customer_id: 客户ID
            existing_order_info: 现有订单信息
            
        Returns:
            Dict: 处理结果
        """
        self.logger.info(f"🛒 开始处理下单任务 - 客户: {customer_id}")
        self.logger.info(f"📝 客户消息: {message}")
        
        try:
            # 提取订单信息
            order_info = self._extract_order_info(message, existing_order_info or {})
            
            # 检查信息完整性
            missing_fields = self._check_missing_fields(order_info)
            
            # 生成回复
            response = self._generate_response(order_info, missing_fields)
            
            # 判断是否信息完整
            is_complete = len(missing_fields) == 0
            
            # 记录处理结果
            result = {
                "task_type": self.task_name,
                "success": True,
                "order_info": order_info,
                "missing_fields": missing_fields,
                "is_complete": is_complete,
                "response": response,
                "customer_id": customer_id,
                "message": message
            }
            
            if is_complete:
                self.logger.info(f"✅ 订单信息收集完成 - 客户: {customer_id}")
            else:
                self.logger.info(f"⏳ 订单信息收集中 - 缺少字段: {missing_fields}")
            
            return result
            
        except Exception as e:
            self.logger.error(f"❌ 下单任务处理失败: {str(e)}")
            return {
                "task_type": self.task_name,
                "success": False,
                "error": str(e),
                "response": "抱歉，下单处理出现异常，请稍后再试。"
            }
    
    def _extract_order_info(self, message: str, existing_info: Dict) -> Dict[str, str]:
        """提取订单信息"""
        order_info = existing_info.copy()
        
        # 提取收货人姓名
        if not order_info.get("receiver"):
            # 简单提取姓名（假设姓名在电话号码前）
            phone_match = re.search(r'1[3-9]\d{9}', message)
            if phone_match:
                phone_start = phone_match.start()
                # 提取电话号码前的2-4个字符作为姓名
                name_part = message[:phone_start].strip()
                if name_part and len(name_part) <= 4:
                    order_info["receiver"] = name_part
        
        # 提取电话号码
        phone_match = re.search(r'1[3-9]\d{9}', message)
        if phone_match:
            order_info["phone"] = phone_match.group()
        
        # 提取地址
        if not order_info.get("address"):
            # 提取包含地址关键词的部分
            address_keywords = ['区', '市', '省', '县', '街道', '路', '号']
            for keyword in address_keywords:
                if keyword in message:
                    # 提取包含地址关键词的完整地址
                    parts = message.split()
                    for part in parts:
                        if keyword in part:
                            order_info["address"] = part
                            break
                    break
        
        # 提取商品信息
        if not order_info.get("product_name"):
            # 提取商品名称
            product_keywords = ['毛衣', '衣服', '裤子', '鞋子', '帽子', '包', '手机', '电脑']
            for keyword in product_keywords:
                if keyword in message:
                    order_info["product_name"] = keyword
                    break
        
        # 提取颜色
        if not order_info.get("color"):
            colors = ['红色', '黄色', '蓝色', '绿色', '紫色', '黑色', '白色', '灰色', '粉色', '橙色']
            for color in colors:
                if color in message:
                    order_info["color"] = color
                    break
        
        # 提取数量
        if not order_info.get("quantity"):
            quantity_match = re.search(r'(\d+)\s*(件|个|台|部|本|张)', message)
            if quantity_match:
                order_info["quantity"] = quantity_match.group(1)
                order_info["quantity_unit"] = quantity_match.group(2)
            else:
                # 只提取数字
                number_match = re.search(r'(\d+)', message)
                if number_match:
                    order_info["quantity"] = number_match.group(1)
        
        return order_info
    
    def _check_missing_fields(self, order_info: Dict[str, str]) -> List[str]:
        """检查缺少的字段"""
        required_fields = ["receiver", "phone", "address", "product_name", "color", "quantity"]
        missing = []
        
        for field in required_fields:
            if not order_info.get(field):
                missing.append(self.order_fields[field])
        
        return missing
    
    def _generate_response(self, order_info: Dict[str, str], missing_fields: List[str]) -> str:
        """生成回复内容"""
        if not missing_fields:
            # 信息完整，确认订单
            return self._generate_complete_order_response(order_info)
        else:
            # 信息不完整，要求补充
            return self._generate_incomplete_order_response(order_info, missing_fields)
    
    def _generate_complete_order_response(self, order_info: Dict[str, str]) -> str:
        """生成完整订单的回复"""
        response = "【快递信息】\n"
        response += f"收货人：{order_info.get('receiver', '')}\n"
        response += f"联系电话：{order_info.get('phone', '')}\n"
        response += f"地址：{order_info.get('address', '')}\n"
        response += "【商品】\n"
        response += f"1. {order_info.get('product_name', '')}，{order_info.get('color', '')}色，数量：{order_info.get('quantity', '')}\n"
        response += "信息已收集齐，这就下单"
        
        return response
    
    def _generate_incomplete_order_response(self, order_info: Dict[str, str], missing_fields: List[str]) -> str:
        """生成不完整订单的回复"""
        response = "【快递信息】\n"
        response += f"收货人：{order_info.get('receiver', 'xxx')}\n"
        response += f"联系电话：{order_info.get('phone', 'xxx')}\n"
        response += f"地址：{order_info.get('address', 'xxx')}\n"
        response += "【商品】\n"
        response += f"1. {order_info.get('product_name', 'xxx')}，{order_info.get('color', 'xx')}色，数量：{order_info.get('quantity', 'xxx')}\n"
        response += f"请补全{', '.join(missing_fields)}信息。"
        
        return response
    
    def get_task_summary(self) -> str:
        """获取任务摘要"""
        return f"📊 下单任务统计：\n- 任务名称：{self.task_name}\n- 处理状态：正常" 